package lion.framework.core.web.views;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import lion.dev.exception.SysException;
import lion.dev.lang.BeanUtil;
import lion.framework.core.bean.BeanFactory;
import lion.framework.core.web.path.PathVar;

/**
 * view支持 type:value这样的前缀形式 如 @View("redirect:/index")
 *
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年5月5日
 */
public class ViewFactory {

	private static Map<String, Class<? extends IView>> viewTypeMap = new HashMap<>();

	public static void regist(String typeName, Class<? extends IView> clazz) {

		viewTypeMap.put(typeName, clazz);
	}

	public static IView createView(String name, String path, String resultType) {

		if (StringUtils.isNotBlank(path) && path.matches("\\w+:.+")) {
			resultType = path.substring(0, path.indexOf(":"));
			path = path.substring(path.indexOf(":") + 1);
		}

		Class<? extends IView> clazz = viewTypeMap.get(resultType);
		if (clazz == null) { return new NoopView(); }

		IView v = null;
		try {
			v = BeanFactory.create(clazz);
		} catch (Exception e) {
			throw new SysException("create view error", e);
		}

		BeanUtil bu = new BeanUtil(v);
		bu.setValue("name", name);
		if (StringUtils.isNotBlank(path)) {
			bu.setValue("path", PathVar.replacePathVars(path));
		}

		return v;
	}
}
